/*
** string.c for  in /home/renard/Dropbox/epitech/dev/projets/systemunix/zappy/zappy-2015-2014s-renard_g/serv-src
**
** Made by guillaume renard
** Login   <renard_g@epitech.net>
**
** Started on  Wed Jun 13 15:22:27 2012 guillaume renard
** Last update Thu Jul 19 18:07:55 2012 pierrick druart
*/

#include	<string.h>
#include	<stdlib.h>

#include	"server.h"
#include	"string.h"

static void	clear(t_string *this)
{
  bzero(this->str, this->size);
  this->size = 0;
}

static void	delete(t_string *this)
{
  if (this->str)
    free(this->str);
  free(this);
}

static int	concat(t_string *this, const char *s2)
{
  this->size += strlen(s2);
  if (this->size >= this->capacity * SIZE_ALLC)
  {
    this->capacity = (this->size / SIZE_ALLC) + 1;
    if ((this->str = realloc(this->str, this->capacity * SIZE_ALLC)) == NULL)
    {
      this->size = 0;
      this->capacity = 1;
      return (-1);
    }
  }
  strcat(this->str, s2);
  return (0);
}

static int	concat_value(t_string *this, int value)
{
  char		tampon[16];

  sprintf(tampon, "%d", value);
  return (this->concat(this, tampon));
}

t_string	*new_string(char *s)
{
  t_string	*this;

  if ((this = xmalloc(sizeof(t_string))) == NULL)
    return (NULL);
  this->size = 0;
  this->capacity = 1;
  if (s)
  {
    this->size = strlen(s);
    this->capacity = (this->size / SIZE_ALLC) + 1;
  }
  this->str = xmalloc(this->capacity * SIZE_ALLC);
  if (s)
    strcpy(this->str, s);
  this->clear = &clear;
  this->concat = &concat;
  this->concat_value = &concat_value;
  this->delete = &delete;
  return (this);
}
